<?php

namespace App\Admin;

use App\Models\Appraise;
use App\Models\Area;
use App\Models\ServiceOrder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class Helper
{
    /**
     * 新增角色权限
     * @param $admin_id
     * @param $role_id
     * @return bool
     */
    public static function addAdminRoles($admin_id,$role_id){
        return DB::table("admin_role_users")->insert([
            'user_id'=>$admin_id,
            'role_id'=>$role_id,
            'created_at'=>now()->toDateTimeLocalString(),
            'updated_at'=>now()->toDateTimeLocalString(),
        ]);
    }

    /**
     * @param $workers
     * @return mixed
     */
    public static function workers( $workers): mixed
    {
        if ($workers){
            foreach ($workers as $worker){
                $worker->image = cdn_url($worker->image);
                $worker->service_count = ServiceOrder::query()
                    ->where("worker_id",$worker->id)
                    ->whereIn("status",[1,2,3])->count();
                $score = Appraise::query()
                    ->where("type",0)
                    ->where("worker_id",$worker->id)
                    ->avg("score");
                $worker->score = floatval($score);
            }
        }
        return $workers;
    }

    public static function findFromDistrictId($district_id): array
    {
        $province_id = 0;
        $city_id = 0;
        $district = Area::whereId($district_id)->first();
        if ($district){
            $city_id = $district->pid;
            $city = Area::whereId($city_id)->first();
            $province_id = $city->pid;
        }
        return [$province_id,$city_id];
    }

    /**
     * @param $time
     * @return array
     */
    public static function getTimeRange($time): array
    {
        switch ($time) {
            case 0:
                $start = now()->format("Y-m-d 00:00:00");
                $end = now()->format("Y-m-d 23:59:59");
                return [$start,$end];
            case 1:
                $start = now()->addDays(-1)->format("Y-m-d 00:00:00");
                $end = now()->addDays(-1)->format("Y-m-d 23:59:59");
                return [$start,$end];
            case 2:
                $start = now()->startOfMonth()->format("Y-m-d 00:00:00");
                $end = now()->endOfMonth()->format("Y-m-d 23:59:59");
                return [$start,$end];
            case 3:
                //总的查询
                return [];
            default:
                $time = explode(" - ",$time);
                $start = Carbon::parse($time[0])->format("Y-m-d 00:00:00");
                $end = Carbon::parse($time[1])->format("Y-m-d 23:59:59");
                return [$start,$end];
        }
    }
}
